<?php
/**
 * SESSION存放数据库
 * @author andery <andery@foxmail.com>
 * @link http://www.Nimo.com/
 * @version $Id: CDbSession.php 2010-07-25 14:34:04Z andery $
 */
class CDbSession implements ISession{
	private $sess_name = '';
    private $sess_id = '';
	private $_db;
	private $_sess_table = 'sz_sess';
	private $_max_life_time = 1440;
	
	public function __construct($sess_name, $sess_id = '')
	{
        $this->sess_name = $sess_name;
        if ($sess_id =='') {
            if (CCookie::get($this->sess_name)) {
                $this->sess_id = CCookie::get($this->sess_name);
            } else {
                $this->_set_sess_id();
                CCookie::set($sess_name,$this->sess_id);
            }
        } else {
            $this->sess_id = $sess_id;
        }
	}
	
    /**
     * 打开
     */
	public function sess_open($save_path, $sess_name)
	{
	    $this->_db = CDb::getInstance();
	    $this->_initSessTable();
	    $this->_setExpire();
	}
	
	/**
	 * 关闭
	 */
	public function sess_close()
	{
	    $this->_db->close();
	}
	
	/**
	 * 存入
	 */
	public function sess_write($sess_id, $sess_data)
	{
	    $expire = $this->_getExpire();
	    $sess_data = addslashes($sess_data);
	    $this->_db->query("REPLACE INTO {$this->_sess_table} (sess_id, expire,data)VALUES('{$this->sess_id}','{$expire}','{$sess_data}')");
        return true;
	}
	
	/**
	 * 读取
	 */
	public function sess_read($sess_id)
	{
	    $row = $this->_db->getAll("SELECT data FROM {$this->_sess_table} WHERE sess_id='{$this->sess_id}'");
        return isset($row[0]['data']) ? $row[0]['data'] : '';
	}
	
	/**
	 * 删除
	 */
	public function sess_destroy()
	{
	    return $this->_db->query("DELETE FROM {$this->_sess_table} WHERE sess_id='{$this->sess_id}'");
	}
	
	/**
	 * 清理过期
	 */
	public function sess_gc($time){
	    $time = time();
	    return $this->_db->query("DELETE FROM {$this->_sess_table} WHERE expire < '{$time}'");
	}
	
	private function _initSessTable()
	{
	    if (CConf::get('session.session_table') != '') {
	        $this->_sess_table = CConf::get('session.session_table');
	    }
	    $tables = $this->_db->get_tables(CConf::get('session.session_dbname'));
	    if (!in_array($this->_sess_table, $tables)) {
            $this->_db->query("CREATE TABLE {$this->_sess_table}(sess_id CHAR(32) PRIMARY KEY,expire INTEGER,data TEXT)");
	    }
	}
	
	private function _set_sess_id()
	{
	    $this->sess_id = md5(uniqid(mt_rand(), true));
	}
	
	/**
	 * 设置过期时间
	 */
	private function _setExpire()
	{
	    if (intval(CConf::get('session.session_max_life_time'))>0) {
	        $this->_max_life_time = CConf::get('session.session_max_life_time');
	    }
	}
	
	/**
	 * 获取过期时间
	 */
	private function _getExpire()
	{
	    return time() + $this->_max_life_time;
	}
}